<template>
  <div class="file-upload-container">

    <div class="upload">
      <!-- 上传对话框标题 -->
      <div class="title">
        <span class="order" v-show="order">{{ order }}</span>
        <span>{{ title }}</span>
        <div class="close-icon" @click="closeUpload">
          <i class="iconfont icon-close"></i>
        </div>
      </div>

      <!-- 上传窗口原始状态 -->
      <div class="file-upload" :class="{'file-upload-coordinate': coordinateFieldShow}">
        <div class="upload" v-if="status === 'upload'">
          <div class="sub-title">选择要上传的文件</div>
          <div class="upload-container">
            <template>
              <form enctype="multipart/form-data">
                <label for="dataUpload">
                  <div class="upload-box" :class="{'dragover': dragover}" @drop.prevent="onDrop" @dragover.prevent="onDragover"
                    @dragleave.prevent="onDragleave">
                    <div class="tips">
                      <i class="iconfont icon-upload"></i>
                      <div>将文件拖至此处 或 <span class="help">点击上传</span>，文件大小不能超过 {{limit >= 1024 ?
                        (parseFloat(limit/1024).toFixed(1) + " GB") : (limit + " MB")}}</div>
                    </div>
                    <p>松开鼠标</p>
                  </div>
                </label>
                <input type="file" id="dataUpload" @change="onFileSelected">
              </form>
            </template>
          </div>
          <div class="discribe"> 支持的文件格式包括：Excel、CSV、SHP(ZIP压缩包)、GeoJSON、KML、GPX</div>
          <div class="discribe"> 大数据量的上传请联系客服或者拨打电话：000000</div>
        </div>

        <!-- 数据上传步骤 -->
        <div class="uploading" v-if="status === 'uploading'">
          <div class="sub-title">正在上传</div>
          <div class="upload-container">
            <div class="upload-box">
              <div class="name">{{selectedFile.name}}</div>
              <div class="progress">{{progress | residue}}%</div>
              <div class="progress-bar" :style="{width:progress + '%'}" :class="{'uploaded':toDatabase}">
              </div>
            </div>
          </div>
        </div>

        <!-- 数据预览步骤 -->
        <div class="preview" v-if="status == 'preview'">
          <data-upload-preview-encoding ref="dataPreviewEncoding" v-if="status === 'preview'" :uid="uploadingDataUid"
            :encoding="uploadingDataEncoding" :offset="selectedOffset" :to-public="toPublic" :selectedFile="selectedFile"
            :fileType="fileType"></data-upload-preview-encoding>
          <div class="back-next">
            <div class="back-wrapper">
              <g-button type="default" @click="backToUpload">重新上传</g-button>
            </div>
            <div class="next-wrapper">
              <g-button type="primary" @click="selectSrs">下一步</g-button>
            </div>
          </div>
        </div>

        <!-- 选择坐标系步骤 -->
        <div class="select-srs" v-if="status === 'select-srs'">
          <div class="upload-option-wrapper">
            <div class="upload-option-title">
              <span>数据将统一转换为GCJ02坐标系，以便与互联网地图正确叠加。请选择数据的原始坐标系</span>
            </div>
            <div class="data-source" v-if="srsSelectorShow">
              <div class="source-container">
                <div>
                  <input id="gaode" type="radio" name="" value="1" v-model="selectedOffset">
                  <label for="gaode">GCJ02坐标系</label>
                  <input id="2000" type="radio" name="" value="3" v-model="selectedOffset">
                  <label for="2000">CGCS2000坐标系</label>
                  <input id="gps" type="radio" name="" value="0" v-model="selectedOffset">
                  <label for="gps">WGS84坐标系</label>
                  <input id="baidu" type="radio" name="" value="2" v-model="selectedOffset">
                  <label for="baidu">百度坐标系</label>
                </div>
              </div>
            </div>
            <div class="select-srs-tips">
              <span>坐标系说明：</span>
              <ul>
                <li>GCJ02坐标系：俗称火星坐标系，高德、腾讯、谷歌等互联网地图均采用该坐标系</li>
                <li>CGCS2000坐标系：2000国家大地坐标系，国家测绘成果均采用该坐标系</li>
                <li>WGS84坐标系：GPS设备采集的数据、谷歌地球均采用该坐标系</li>
                <li>百度坐标系：百度地图所采用的坐标系</li>
              </ul>
            </div>
          </div>
          <div class="toolbar">
            <div class="back-wrapper">
              <g-button type="default" @click="backToPreview">上一步</g-button>
            </div>
            <div class="next-wrapper">
              <g-button type="primary" @click="startImport">开始入库</g-button>
            </div>
          </div>
        </div>

        <!-- 正在入库步骤 -->
        <div class="uploading" v-if="status === 'importing'">
          <div class="sub-title">正在入库</div>
          <div class="upload-container">
            <div class="upload-box">
              <div class="name">{{selectedFile.name}}</div>
              <!-- <div v-if="withProgress(selectedFile.name)" class="progress">{{progress | residue}}%</div> -->
              <div class="progress">{{progress | residue}}%</div>
              <div class="progress-bar" :style="{width:progress + '%'}" :class="{'uploaded':toDatabase}">
              </div>
            </div>
          </div>
          <div class="import-tips">关闭此窗口不影响数据入库</div>
        </div>

        <!-- 完成上传 -->
        <div class="upload-success" v-if="status === 'success'">
          <div class="upload-success-tip">
            <div class="file-name">
              <span class="iconfont icon-success-fill"></span><span class="file-name-text"> {{ selectedFile.name }}
                已上传成功！</span>
            </div>
            <g-button type="primary" @click="backToUpload">继续上传</g-button>
            <g-button type="default" @click="close">确定</g-button>
          </div>
        </div>

        <!-- 错误提示 -->
        <div class="error-msg-tips-wrapper" v-if="status === 'error' && error">
          <data-upload-error :msg-tips="error"></data-upload-error>
        </div>
      </div>

    </div>
  </div>
</template>

<script>
  import axios from 'axios'
  import Bus from '@/utils/event_bus'
  import GButton from '@/components/common/g-button'
  import GScrollbar from '@/components/common/g-scrollbar'
  import jschardet from 'jschardet'
  import DataUploadPreview from './data-upload-preview'
  import DataUploadPreviewEncoding from './data-upload-preview-encoding'
  import DataUploadError from './data-upload-error'
  import constant from '@/config/constant.js'
  import SparkMD5 from 'spark-md5'
  import {
    upload as uploadAPI,
    job as jobAPI
  } from '@/api';
  import {
    setTimeout
  } from 'timers';

  const qs = require('qs');
  const axiosInstance = axios.create({
    baseURL: '/s/data/',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    }
  });
  const previewRowNum = 11;
  const dataTypes = ['string', 'long', 'double', 'date', 'boolean', 'unknown'];
  const ERR_FILE_ILLEGAL = "文件无法识别";
  const ERR_FILE_SIZE_EXCEED = '抱歉，暂不支持上传超过 200MB 的文件';

  export default {

    name: 'upload',

    components: {
      GButton,
      DataUploadPreview,
      GScrollbar,
      DataUploadPreviewEncoding,
      DataUploadError
    },

    data: function () {
      //每个切片文件大小
      const chunkSize = 5 * 1024 * 1024;

      const sliceSize = 100 * 1024 * 1024;
      return {
        title: '选择文件',
        order: '1/4',
        status: 'upload',
        limit: 1024,
        progress: 0,
        toDatabase: false,
        storageTimes: undefined,
        dragover: false,
        selectedFile: '',
        selectedFileNameWithoutSuffix: '',
        selectedOffset: 1,
        selectedEncoding: 'utf-8',
        fields: [],
        fieldTypes: [],
        previewData: null,
        // accept: "application/zip,text/csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.geo+json, application/vnd.google-earth.kml+xml, application/vnd.google-earth.kmz, application/gpx+xml, text/gpx+xml, application/json",
        suffixs: ['csv', 'xls', 'xlsx', 'kml', 'kmz', 'gpx', 'json', 'geojson', 'zip'],
        suffix: '',
        readAsBinaryExist: false,
        webWorkerExist: false,
        pending: false,
        dataPreVizShow: false,
        sheetArray: [],
        sheetDataLoading: false,
        dataRowNumEnough: false,
        fileIsExcel: false,
        fileIsCSV: false,
        fieldNames: [],
        CSVEncoding: 'utf-8',
        previewShow: false,
        uploadingDataUid: null,
        uploadingDataEncoding: null,
        uid: null,
        errorMessage: '出错了', // 出错信息
        errorTips: [], // 出错建议
        error: null,
        srsSelectorShow: true,
        chunkSize: chunkSize,
        uploadProgress: [],
        progress: 0, //进度
        proportion: 0, //已发送切片数目
        sliceSize: sliceSize,
        xField: null,
        yField: null
      }
    },
    computed: {
      fileType() {
        return this.guessFileType(this.selectedFile.name);
      },

      coordinateFieldShow() {
        if (['select-srs', 'uploading', 'importing', 'success', 'error'].includes(this.status)) return true;
        if (['csv', 'xls', 'xlsx'].includes(this.suffix)) return false;
        return true;
      },
    },

    props: {
      toPublic: {
        type: Boolean,
        default: false
      }
    },
    filters: {
      residue(value) {
        if (!value) return 0;
        return Math.floor(value);
      }
    },
    methods: {
      /**
       * @description 更改列信息
       * @param {string} cellName 列名称
       * @param {string} cellType 列类型
       * @param {string} index 列索引
       */
      changePostParam(cellName, cellType, index) {
        this.fieldNames[index] = cellName;
        this.fieldTypes[index] = cellType;
      },

      /**
       * @description 关闭上传对话框
       */
      close() {
        Bus.$emit('close-upload-panel');
      },

      onDragover() {
        this.dragover = true;
      },

      onDragleave() {
        this.dragover = false;
      },

      // 用户以拖拽方式选择文件
      onDrop(evt) {
        this.dragover = false;
        if (!evt.dataTransfer || !evt.dataTransfer.files) {
          this.$message.error(ERR_FILE_ILLEGAL);
          return;
        }
        let files = evt.dataTransfer.files;

        if (files.length > 1) {
          this.$message.error('一次只能选择一个数据');
          evt.dataTransfer.clearData();
          return;
        }

        this.selectedFile = files[0];
        this.handleSelectedFile();
      },

      // 用户以选择方式选择文件
      onFileSelected(evt) {
        if (!evt.target || !evt.target.files || evt.target.files.length <= 0) {
          this.$message.error(ERR_FILE_ILLEGAL);
          return;
        }
        this.selectedFile = evt.target.files[0];
        this.handleSelectedFile();
      },

      reselect() { // 重新选择文件
        this.selectedFile = '';
        this.progress = 0;
        this.status = 'upload';
        this.dataPreVizShow = false;
        this.sheetArray = [];
      },

      handleSelectedFile() { // 上传文件预览
        this.xField = null;
        this.yField = null;
        let file = this.selectedFile;
        if (!file) {
          return;
        }
        this.startUpload();
      },

      fixdata(data) {
        var o = "",
          l = 0,
          w = 10240;
        for (; l < data.byteLength / w; ++l)
          o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(o.length)));
        return o;
      },

      /** 
       * @description 触发上传文件操作
       */
      startUpload() {
        let file = this.selectedFile;
        if (!file || file.size > this.limit * 1024 * 1024) {
          this.$message.error(
            `上传文件大小不能超过：${this.limit > 1024 ? ((this.limit/1024).toFixed(1) + ' GB') : (this.limit + ' MB') }`);
          this.reselect();
          return;
        }
        this.status = 'uploading';

        if (file.size < this.sliceSize) {
          this.uploadByFile(file);
        } else {
          this.uploadBySlice(file);
        }
      },

      async checkExist(hash) {

        let result = await uploadAPI.exists(hash);

        if (!result || result.data.code) {
          return null;
        }

        return result;
      },

      async getFileHash(file) {

        return new Promise((resolve, reject) => {

          let fileReader = new FileReader();

          fileReader.readAsBinaryString(file);

          fileReader.onload = (e) => {

            let md5 = SparkMD5.hashBinary(e.target.result)
            resolve(md5);

          }

          fileReader.onerror = () => {
            resolve()
          }
        })

      },

      /** 
       * @description 上传文件到服务器
       * @param {object} file 待上传文件
       */
      async uploadByFile(file) {
        let self = this;
        let encoding = 'utf-8';

        let formData = new FormData();
        formData.append('file', file);

        let config = {
          responseType: 'json',
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: function (progressEvt) {

            self.progress = Math.round((progressEvt.loaded * 100) / progressEvt.total);

            // if (self.progress === 100) {
            //     setTimeout(() => {
            //         this.status = 'preview';
            //     }, 900);
            // }
          }
        };

        axios.post('/s/file/', formData, config)
          .then((result) => {
            if (!result || result.data.code != 0) {
              this.error = constant.uploadErr['451'];
              this.status = 'error';
              return;
            }

            let data = result.data.data;

            let uid = data.uid;

            if (!uid) {
              this.error = constant.uploadErr['451'];
              this.status = 'error';
              return;
            }

            this.uid = uid;
            this.showPreview(uid, encoding);
          }).catch((err) => {
            this.error = constant.uploadErr['451'];
            this.status = 'error';
          });

      },

      async uploadBySlice(file) {

        let uid = await this.initSliceUpload(file);

        if (!uid) {
          this.error = constant.uploadErr['451'];
          this.status = 'error';
          return;
        }

        let chunkSize = this.chunkSize;
        let chunkCount = Math.ceil(file.size / chunkSize);
        let currentChunk = 0;
        let fileReader = new FileReader();

        function loadNext() {
          let start = currentChunk * chunkSize;
          let end = (start + chunkSize) >= file.size ? file.size : start + chunkSize;
          fileReader.readAsArrayBuffer(file.slice(start, end));
        }

        fileReader.onload = async (evt) => {

          currentChunk++;
          this.proportion++;
          this.progress = parseInt(this.proportion / chunkCount * 10);

          if (currentChunk < chunkCount) {
            loadNext();
          } else {

            //切片上传文件
            this.proportion = chunkCount / 10;

            this.uploadProgress = [];
            for (let i = 0; i < chunkCount; i++) {
              let start = i * chunkSize;
              let end = (start + chunkSize) >= file.size ? file.size : (start + chunkSize);
              this.sendFile(uid, i, chunkCount, file.slice(start, end));
            }
          }
        }

        loadNext();
      },

      async initSliceUpload(file) {

        let hash = await this.getFileHash(file);

        let result = await uploadAPI.initUpload(hash, file.name, this.suffix);

        if (!result || result.data.code != 0) {
          this.error = constant.uploadErr['451'];
          this.status = 'error';
          return;
        }

        let uid = result.data.data.uid;

        return uid;
      },

      /**
       * 上传文件切片
       */
      async sendFile(uid, order, count, chunkFile) {
        let formData = new FormData();
        formData.append('file', chunkFile);

        let params = {
          uid,
          order,
          count
        }

        let result = await uploadAPI.sliceUpload(formData, params, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
        });

        if (!result || result.data.code != 0) {
          this.error = constant.uploadErr['451'];
          this.status = 'error';
          return;
        } else {

          this.uploadProgress.push(order);
          this.proportion++;
          this.progress = parseInt(this.proportion / count * 90);

          if (count === this.uploadProgress.length) {
            return this.mergeFile(uid);
          }
        }

      },

      /**
       * 合并切片文件
       */
      async mergeFile(mergeId) {

        let result = await uploadAPI.merge(mergeId);

        if (!result || result.data.code != 0) {
          this.error = constant.uploadErr['451'];
          this.status = 'error';
          return;
        } else {
          //预览文件
          this.uid = result.data.data.uid;
          this.showPreview(this.uid, 'utf-8');
          return;
        }
      },

      /** 
       * @description 显示数据预览框
       * @param {string} uid 数据uid
       * @param {string} encoding 数据编码
       */
      showPreview(uid, encoding) {
        this.uploadingDataUid = uid;
        this.uploadingDataEncoding = encoding;
        this.status = 'preview';
      },

      /**
       * @augments 获取导入数据库状态
       * @param {string} uid job uid
       */

      getImportStatus(uid) {
        this.progress = 0;

        let accessAllowed = true;
        let importState = setInterval(() => {

          if (!accessAllowed) {
            return;
          }
          accessAllowed = false;
          jobAPI.job(uid)
            .then((res) => {
              accessAllowed = true;

              let result = res.data.data;
              switch (result.status) {
                case 'created':
                case 'started':
                case 'percent':
                  {
                    this.progress = result.percent;
                    break;
                  }
                case 'success':
                  {
                    this.progress = 100;
                    let percentTimeout = setTimeout(() => {
                      Bus.$emit('geofile-upload-success');
                      this.status = 'success';
                      clearTimeout(percentTimeout);
                    }, 1500);
                    clearInterval(importState);
                    break;
                  }
                case 'fail':
                  this.error = {
                    msg: '上传失败',
                    tips: [result.msg]
                  };
                  this.status = 'error';
                  clearInterval(importState);
                  break;
                default:
                  {
                    this.error = {
                      msg: '上传失败',
                      tips: [result.msg]
                    };
                    this.status = 'error';
                    clearInterval(importState);
                    break;
                  }
              }
            })
            .catch((err) => {
              this.error = {
                msg: '上传失败',
                tips: [err]
              };
              this.status = 'error';
              clearInterval(importState);
            });
        }, 2500);
      },

      /**
       * @description 解析字符串中包含的原始数据类型: string, double, long, date
       * @param {string} str 原始类型
       * @return {string}
       */
      parseType: function (str) {
        if (!isNaN(str)) {
          let number = Number(str);
          if (Number.isInteger(number)) {
            return 'long';
          } else {
            return 'double';
          }
        }
        if (Date.parse(str)) {
          return 'date';
        }
        return 'string';
      },

      /** 
       * @description 检查文件内容编码
       * @param {object} file 文件对象
       * @param {function} callback 检查完毕执行的回调函数
       */
      checkEncoding(file, callback) { // 检查内容的编码

        let fileReader = new FileReader();
        if (!fileReader) {
          this.$message.error('读取失败，请升级您的浏览器');
          this.reselect();
          return;
        }

        fileReader.onload = (evt) => {
          let data = evt.target.result;
          let encoding = jschardet.detect(data);

          if (encoding == "windows-1252") {
            encoding.encoding = 'ANSI';
          }
          callback(encoding.encoding);
        };

        fileReader.onerror = (evt) => {
          this.$message.error('您上传的文件内容有问题');
          this.reselect();
          return;
        };

        fileReader.readAsBinaryString(file);

      },

      /**
       * @description 关闭上传框
       */
      closeUpload() {
        Bus.$emit('close-upload-panel');
      },

      /**
       * 确认文件类型
       * @param {string} fileName 文件名
       * @return {string} 文件类型
       */
      // withProgress(fileName) {
      //     return !(/\.csv$/.test( fileName ) || /\.xlsx?$/.test( fileName ));
      // },

      /**
       * 进入选择坐标系步骤
       */
      selectSrs() {
        if (['csv', 'xls', 'xlsx'].includes(this.suffix) && this.xField && this.yField && this.xField == this.yField) {
          this.$message.error('经纬度字段不能为同一字段');
          return;
        }

        this.fields = this.$refs.dataPreviewEncoding.fields;
        this.fieldTypes = this.$refs.dataPreviewEncoding.fieldTypes;
        this.previewData = this.$refs.dataPreviewEncoding.previewData;

        if ((this.suffix == 'csv' || this.suffix == 'xls' || this.suffix == 'xlsx') && (!this.xField || !this.yField)) {
          this.status = 'importing';
          this.startImport();
        } else {
          this.status = 'select-srs';
        }

      },

      /**
       * 返回上传文件步骤
       */
      backToUpload() {
        this.status = 'upload';
      },

      /**
       * 返回到预览步骤
       */
      backToPreview() {
        this.status = 'preview';
      },

      /**
       * 开始数据入库
       */
      async startImport() {

        let fileName = this.selectedFile.name;

        let params = (this.fileType == 'csv' || this.fileType == 'excel') ? {
          name: `geohey-data-import`,
          params: JSON.stringify({
            dataUid: this.uid,
            dataName: fileName,
            fileType: this.fileType,
            fields: this.fields,
            // fieldTypes: this.fieldTypes,
            encoding: this.selectedEncoding,
            offset: this.selectedOffset,
            toSchema: this.publicUpload ? 'public_data' : 'data',
            xField: this.xField,
            yField: this.yField
          })
        } : {
          name: `geohey-data-import`,
          params: JSON.stringify({
            dataUid: this.uid,
            dataName: fileName,
            fileType: this.fileType,
            fields: this.fields,
            // fieldTypes: this.fieldTypes,
            encoding: this.selectedEncoding,
            offset: this.selectedOffset,
            toSchema: this.publicUpload ? 'public_data' : 'data',
          })
        }

        try {
          let result = await jobAPI.create(`${this.toPublic ? 'public-': ''}data-import`, params);
          if (!result || result.data.code !== 0) {
            console.log(result);
            this.error = constant.uploadErr['500'];
            this.status = 'error';
            return;
          }

          let jobUid = result.data.data.uid;
          this.getImportStatus(jobUid);

          this.status = 'importing';

        } catch (ex) {
          console.log(`入库失败`);
        }
      },

      /**
       * 确认文件类型
       * @param {string} fileName 文件名
       * @return {string} 文件类型
       */
      guessFileType(fileName) {
        let fileType = null;
        if (!fileName) return;
        fileName = fileName.toLowerCase();
        if (/\.csv$/.test(fileName)) {
          fileType = 'csv';
        }
        if (/\.xlsx?$/.test(fileName)) {
          fileType = 'excel';
        }
        if (/\.zip$/.test(fileName)) {
          fileType = 'shp';
        }
        if (/\.geojson$/.test(fileName)) {
          fileType = 'geojson';
        }
        if (/\.json$/.test(fileName)) {
          fileType = 'json';
        }
        if (/\.kml$/.test(fileName)) {
          fileType = 'kml';
        }
        if (/\.gpx$/.test(fileName)) {
          fileType = 'gpx';
        }
        return fileType;
      },
    },

    watch: {

      selectedFile() {

        let file = this.selectedFile;

        if (!file) {
          return;
        }

        if (file.size / 1048576 > this.limit) {
          this.$message.error(
            `抱歉，暂不支持上传超过 ${this.limit > 1024 ? (parseFloat(this.limit / 1024).toFixed(1) + " GB") : (this.limit + " MB")} 的文件`
          );
          this.selectedFile = '';
          return;
        }

        this.selectedFileNameWithoutSuffix = file.name.substring(0, file.name.lastIndexOf('.'));
        let suffix = file.name.split('.').pop().toLowerCase();

        if (!this.suffixs.includes(suffix)) {
          this.$message.error('您选择的数据格式不正确');
          this.selectedFile = '';
          return;
        }

        this.suffix = suffix;
        this.status = 'uploading';
      },

      status() {
        if (this.status === 'upload') {
          this.suffix = '';
          this.progress = 0;
          this.title = '上传文件';
          this.order = `1/4`;
        } else if (this.status === 'preview') {
          this.progress = 0;
          this.title = `数据预览`;
          this.order = `2/4`;
        } else if (this.status === 'select-srs') {
          this.title = '选择坐标系';
          this.order = `3/4`;
        } else if (this.status === 'importing') {
          this.title = `数据入库`;
          this.order = `4/4`;
        } else if (this.status === 'success') {
          this.title = `入库成功`;
          this.order = null;
        } else if (this.status === 'error') {
          this.title = `上传出错`;
          this.order = null;
        } else {
          this.title = '上传文件';
          this.order = `1/4`;
        }
      },

    },

    created() {

      let uploadLimit = this.$root.geohey.upload_limit;
      if (uploadLimit && ('upload_limit' in uploadLimit)) {
        this.limit = uploadLimit.upload_limit;
      }

      // 返回上传界面
      Bus.$off('back-to-upload');
      Bus.$on('back-to-upload', () => {
        this.progress = 0;
        this.status = 'upload';
      });

      // 预览数据出错
      Bus.$off('preview-data-file-error');
      Bus.$on('preview-data-file-error', msgTips => {
        this.error = msgTips;
        this.status = 'error';
      });

      // 上传出错重新上传事件
      Bus.$off('re-upload-after-error');
      Bus.$on('re-upload-after-error', () => {
        this.progress = 0;
        this.status = 'upload';
      });

      // 关闭预览，继续上传事件
      Bus.$off('preview-dialog-close');
      Bus.$on('preview-dialog-close', (uid) => {

        this.title = '正在入库';
        this.status = 'importing';
        this.toDatabase = true;
        this.getImportStatus(uid);

      });

      // 返回上传界面
      Bus.$off('back-to-upload');
      Bus.$on('back-to-upload', () => {
        this.progress = 0;
        this.status = 'upload';
      });

      // 预览数据出错
      Bus.$off('preview-data-file-error');
      Bus.$on('preview-data-file-error', msgTips => {
        this.error = msgTips;
        this.status = 'error';
      });

      // 上传出错重新上传事件
      Bus.$off('re-upload-after-error');
      Bus.$on('re-upload-after-error', () => {
        this.progress = 0;
        this.status = 'upload';
      });

      // 获取预览数据出错事件
      Bus.$off('preview-data-get-error');
      Bus.$on('preview-data-get-error', (msgTips) => {
        this.error = msgTips;
        this.status = 'error';
      });

      // 用户选择编码事件
      Bus.$off('data-upload-change-encoding');
      Bus.$on('data-upload-change-encoding', (fields, fieldTypes, encoding) => {
        this.fields = fields;
        this.fieldTypes = fieldTypes;
        this.selectedEncoding = encoding;
      });

      Bus.$off('coordinate-xField');
      Bus.$on('coordinate-xField', (xField) => {
        this.xField = xField;
      });
      Bus.$off('coordinate-yField');
      Bus.$on('coordinate-yField', (yField) => {
        this.yField = yField;
      });
    },

  }

</script>

<style lang="scss" rel="stylesheet/scss">
  @import "common";
  $uploadBorder: #aeaeae;
  $uploadBackground: #F4F8FB;
  $bgProgress: #dce7f4;
  $bgUploaded: #dcf4f4;

  .file-upload-container {

    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    bottom: 0;
    background: rgba(0, 0, 0, .5);
    z-index: 3000;

    .g-scrollbar .g-scrollbar-wrapper {
      //   width: calc(100% - 10px) !important;
      height: calc(100% - 10px) !important;
    }

    .upload {
      width: 100%;
      height: 100%;
      //   max-width: 700px;

      //   max-height: 420px;
      max-width: 800px;
      max-height: 480px;
      position: absolute;
      margin: auto;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      overflow: hidden;
      background-color: white;
      border-radius: 3px;

      .title {
        @include text-overflow;
        overflow: hidden;
        width: 100%;
        height: 48px;
        line-height: 48px;
        padding: 0px 12px;
        position: absolute;
        z-index: 100;
        top: 0;
        left: 0;
        background-color: $bgWhite;
        border-top-left-radius: $bdRadius;
        border-top-right-radius: $bdRadius;

        .order {
          width: 32px;
          height: 32px;
          background: $primary;
          border-radius: 50%;
          color: #fff;
          display: inline-block;
          margin-top: 8px;
          margin-right: 4px;
          text-align: center;
          line-height: 32px;
        }

        .close-icon {
          float: right;
          cursor: pointer;

          &:hover {
            color: $primary;
          }

          >i {
            font-size: 20px;
          }
        }

        >span {
          font-size: $fontSizeBase;
          font-weight: 500;
          float: left;
        }

      }

      .file-upload {

        position: relative;
        margin-top: 48px;
        padding: 12px;
        height: calc(100% - 48px);


        .upload,
        .uploading,
        .select-srs {
          width: 100%;
          height: 100%;

          .select-srs-tip {
            font-size: 13px;
            padding: 4px 8px;
            font-weight: bold;
          }

          >div.discribe {
            width: 100%;
            text-align: center;
            margin-bottom: 16px;
          }

          .data-loading {
            font-size: 16px;
            margin-top: 124px;
            width: 100%;
            text-align: center;

            >span {
              font-size: 12px;
            }
          }

          .data-preview-scrollbar {
            height: 100%;
            width: 100%;


            .data-table {
              width: 100%;
              text-align: center;
              margin-bottom: 10px;
              border-right: 1px solid #e6e9f0;
              border-bottom: 1px solid #e6e9f0;
            }

          }

          .data-preview-tips {
            position: absolute;
            left: 16px;
            bottom: -16px;
            color: #889;
          }

        }

        .upload {

          padding-top: 112px;

          .sub-title {
            color: $dark;
            font-size: 16px;
            text-align: center;
            @include user-select(none);
            padding-bottom: 16px;
          }

          .discribe {
            color: $gray;
            font-size: 12px;
            @include user-select(none);

            &.dragover {
              display: none;
            }
          }

          .upload-container {

            padding-bottom: 16px;

            .upload-box {
              width: 86%;
              overflow: hidden;
              min-width: 200px;
              height: 176px;
              border: 1px dashed $uploadBorder;
              border-radius: $bdRadius;
              background-color: $uploadBackground;
              margin: 0 auto;
              font-size: 12px;
              line-height: 54px;
              padding: 0 auto;
              position: relative;
              cursor: pointer;
              @include transition(all .3s);

              .tips {

                width: 354px;
                height: 58px;
                overflow: hidden !important;
                position: absolute;
                margin: auto;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                overflow: auto;

                div {
                  display: inline;
                  position: absolute;
                }

                .iconfont {
                  font-size: 32px;
                  margin: 0 8px 0 0;
                }
              }



              >div:first {
                height: 90px;
              }

              >p {
                display: none;
              }

              &:hover {
                border: 1px dashed $primary;
              }

              &.dragover {
                border: 1px dashed $lightPrimary;

                background-color: darken($uploadBackground, 2%);
              }
            }

            #dataUpload {
              opacity: 0;
              display: none;
            }
          }
        }

        .select-srs {


          .upload-option-wrapper {
            height: 190px;
            width: 500px;
            position: absolute;
            margin: auto;
            left: 0;
            right: 0;
            top: 110px;
            vertical-align: middle;

            .upload-option-title {
              text-align: left;
              padding-left: 12px;
            }

            .select-srs-tips {
              position: absolute;
              width: 480px;
              left: 12px;

              ul {
                margin-left: 12px;
                color: $gray;
              }

              ul li {
                list-style-type: disc;
              }

              span {
                display: inline-block;
                padding: 0 0 8px 0;
              }

              p {
                color: $gray;
                padding: 2px 0;
              }
            }

          }


          .upload-container {

            // margin-top: 60px;
            margin-bottom: 25px;

            .upload-box {
              width: 70%;
              overflow: hidden;
              min-width: 200px;
              height: 56px;
              border: 1px dashed $uploadBorder;
              border-radius: $bdRadius;
              background-color: $uploadBackground;
              margin: 0 auto;
              font-size: 14px;
              line-height: 54px;
              padding: 0 24px;
              cursor: pointer;
              color: $dark;

              >div {
                float: left;
              }
            }
          }

          .data-source {
            text-align: left;

            .source-container {
              width: 600px;
              margin: 0 auto;
              padding: 60px 0;
              overflow: hidden;
              min-width: 200px;
              color: black;
              font-size: 12px;

              input {
                margin-top: 3.5px;
              }

              .tip {
                padding: 16px 2px;
              }

              >div {
                float: left;
              }

              input {
                margin-left: 12px;
                margin-right: 4px;
              }

              .help {
                float: right;
              }
            }
          }

          .option {

            .option-container {

              width: 320px;
              margin: 20px auto;
              text-align: center;
              overflow: hidden;
              position: relative;

              >div {
                float: left;
                width: 120px;
                margin: 0 14px;

                button {
                  width: 100%;
                }
              }
            }
          }
        }

        .uploading {

          padding-top: 130px;

          .sub-title {
            color: $dark;
            font-size: 16px;
            text-align: center;
            @include user-select(none);
            padding-bottom: 16px;
          }

          .upload-container {

            position: relative;

            .upload-box {
              width: 70%;
              position: relative;
              overflow: hidden;
              min-width: 200px;
              height: 48px;
              border: 1px dashed $uploadBorder;
              border-radius: $bdRadius;
              background-color: $uploadBackground;
              margin: 0 auto;
              font-size: 12px;
              line-height: 48px;
              padding: 0 24px;
              cursor: pointer;
              color: $dark;

              >div {
                height: 100%;
                position: absolute;
              }

              .name {
                @include text-overflow;
                display: inline-block;
                z-index: 20;
                width: 50%;
                overflow: hidden;
                left: 24px;
              }

              .database {
                display: inline-block;
                color: $primary;
                z-index: 20;
                right: 20px;

                >i {
                  position: absolute;
                  right: 118px;
                }
              }

              .progress {
                display: inline-block;
                color: $primary;
                z-index: 20;
                right: 20px;
              }

              .progress-bar {
                background-color: $bgProgress;
                z-index: 19;
                top: 0;
                left: 0;
                @include transition(all .5s);

                &.uploaded {
                  background-color: $bgUploaded;
                }
              }
            }

          }

          .import-tips {
            position: absolute;
            left: 20px;
            bottom: 20px;
            color: #889;
          }
        }

        .upload-success {

          .upload-success-tip {
            width: 577.917px;
            height: 176px;
            position: absolute;
            left: 0;
            right: 0;
            bottom: 0;
            top: 0;
            margin: auto;
            background-color: #f4f8fb;
            border: 1px dashed #bbb;
            border-radius: 3px;
            text-align: center;
            padding-top: -2px;

            .g-button {
              margin: 4px;
            }

            div.file-name {
              font-size: 12px;
              padding: 56px 0 12px 12px;
              text-align: center;
              display: flex;
              align-items: center;
              justify-content: center;

              .file-name-text {
                line-height: 17px;
                margin-left: 4px;
              }

              span.iconfont {
                color: $success;
                font-size: 18px;
              }
            }

            div.continue {
              color: #5393f7;
              cursor: pointer;
              padding: 8px 12px;
            }
          }

          .confirm {
            position: absolute;
            bottom: 18px;
            right: 10px;
          }
        }

        .error-msg-tips-wrapper {
          height: 100%;
        }

        .help {
          color: $primary;
          cursor: pointer;
        }
      }
    }

    .back-next {
      position: absolute;
      z-index: 100;
      right: 0px;
      bottom: 6px;
      height: 50px;
      color: black;
    }

    .back-wrapper {
      position: absolute;
      top: 2px;
      left: calc(100% - 166px);
    }

    .next-wrapper {
      position: absolute;
      top: 2px;
      left: calc(100% - 86px);
      display: inline-block;
    }

    .toolbar {
      position: absolute;
      bottom: 64px;
      right: 0;
    }


  }

  .file-upload-coordinate {
    margin-top: 8px !important;
    height: 100% !important;
  }

</style>
